<?php

namespace App\Http\Controllers\Home;

use App\Http\Controllers\Controller;
use App\Models\BalanceLogs;
use App\Models\Configs;
use App\Models\Goods;
use App\Models\IntegralLogs;
use App\Models\Mails;
use App\Models\OrderPays;
use App\Models\Activitys;

use App\Models\Orders;
use App\Models\ProfitLogs;
use App\Models\SignUps;
use App\Models\Stores;
use App\Models\Users;
use App\Models\Wechat;
use EasyWeChat\Factory;
use Illuminate\Support\Facades\Log;

class PaymentController extends Controller
{
    public $wxConfig;

    public function __construct()
    {

        $wx_config = config("wechat.payment.default");
        $this->wxConfig = $wx_config;
    }

    //JSAPI
    public function wxJSAPI(){
        $config = config("wechat.official_account.default");
        $app = Factory::officialAccount($config);
        $ret = $app->jssdk->buildConfig(array('updateAppMessageShareData', 'updateTimelineShareData'), true);
        return [
            'code' => 1,
            'msg' => "生成JSAPI成功",
            'data' => $ret
        ];
    }

    //需要调用微信支付时调用该方法
    public function wxPayment($pay_sn='',$product_id='',$price=0,$title='',$detail='',$notify_url = '',$type='NATIVE',$open_id=''){

        $attributes = [
            'trade_type'       => $type,
            'body'             => $title,
            'detail'           => $detail,
            'out_trade_no'     => $pay_sn,
            'product_id'        => $product_id,
            'total_fee'        => $price*100,
            'notify_url'       => $notify_url,
            'openid'          => $open_id
        ];
        Log::info($attributes);
        $app = Factory::payment($this->wxConfig);

        $result = $app->order->unify($attributes);
        Log::info($result);
        if( $result['return_code'] == 'SUCCESS' && $result['result_code'] == 'SUCCESS'){
            if($type=='NATIVE'){
                return [
                    'code' => 1,
                    'msg' => "生成支付二维码成功",
                    'data' => $result['code_url'],
                ];
            } elseif($type=='JSAPI'){
                $result = $app->jssdk->sdkConfig($result['prepay_id']); // 返回数组//第二次签名
                return [
                    'code' => 1,
                    'msg' => "生成支付订单成功",
                    'data' => $result
                ];
            }
        } else{
            Log::error('微信支付签名失败:',$result);
            return ["code"=>0, "msg"=>"支付订单生成失败"];
        }
    }

    /**
     * 商品支付回调
     */
    public function goodsNotifyUrl()
    {
        $app = Factory::payment($this->wxConfig);
        $response = $app->handlePaidNotify(function ($message, $fail) {
            //处理订单
            Log::info('微信支付回调:',$message);
            if ($message["result_code"] == "SUCCESS" && $message["return_code"]) {
                try{
                    //循环修改订单状态
                    $order_info = Orders::where("pay_sn", $message["out_trade_no"])->get();
                    $pay_info = OrderPays::where("pay_sn", $message["out_trade_no"])->first();
                    if($pay_info["pay_status"]==0){
                        $pay_info->pay_status = 1;
                        $pay_info->save();
                        foreach ($order_info as $key=>$val){
                            if($val['pay_status'] == 1){
                                $updata_arr = [];
                                $updata_arr['pay_status'] = 2;
                                $updata_arr['pay_time'] = date('Y-m-d H:i:s');
                                $updata_arr['order_state'] = 3;
                                Orders::where("pay_sn", $val['pay_sn'])->update($updata_arr);
                            }
                        }

                        //hr赠送积分
                        $integral = Configs::getConfig('integral');
                        Users::where('id',$order_info[0]['user_id'])->increment('integral',$integral['hr_goods']);
                        //发送站内信-积分增加通知
                        $template = [
                            'title' => '购买商品获得积分',
                            'content' => '您购买的商品获得"' . $integral['hr_goods'] .'"积分，支付单号为：'. $order_info[0]['pay_sn'],
                            'user_id' => $order_info[0]['user_id'],
                            'status' => 1,
                            'type' => 1,
                        ];
                        Mails::create($template);
                        //积分日志记录
                        $integral = [
                            'user_id' => $order_info[0]['user_id'],
                            'user_name' => $order_info[0]['user_name'],
                            'integral' => '+'.$integral['hr_goods'],
                            'desc' => '购买商品获得积分',
                            'type' => 1,
                        ];
                        IntegralLogs::create($integral);
                    }

                    return 'SUCCESS';// 返回处理完成
                }catch (\Exception $e) {
                    Log::info($e->getMessage());
                }
            }
        });

        return $response;
    }

    /**
     * 活动支付回调
     */
    public function actNotifyUrl()
    {
        $app = Factory::payment($this->wxConfig);
        $response = $app->handlePaidNotify(function ($message, $fail) {
            //处理订单
            Log::info('微信活动支付回调:',$message);
            if ($message["result_code"] == "SUCCESS" && $message["return_code"]) {
                try{
                    //支付单信息
                    $pay_info = SignUps::where("pay_sn", $message["out_trade_no"])->first();
                    if($pay_info["pay_state"]==1){
                        //修改订单信息
                        $pay_info->pay_state = 2;
                        $pay_info->pay_way = 2;
                        $pay_info->pay_at = date('Y-m-d H:i:s');
                        $pay_info->save();

                        $integrals = Configs::getConfig('integral');
                        $act_info = Activitys::where('id',$pay_info['activity_id'])->first(['user_id','title','place','start_at']);//活动具体信息
                        $user = Users::where('id',$act_info['user_id'])->first(['username','openid']);//发布活动人信息
                        //活动人数积分等处理
                        Activitys::where('id',$pay_info['activity_id'])->increment('number',$pay_info['number']);//报名人数加
                        Users::where('id',$pay_info['user_id'])->increment('integral',$integrals['hr_activity']);//报名活动送积分
                        //添加日志记录
                        $integral = [
                            'user_id' => $pay_info['user_id'],
                            'user_name' => $pay_info['user_name'],
                            'integral' => '+'.$integrals['hr_activity'],
                            'type' => 1,
                            'desc' => '报名活动送积分',
                        ];
                        IntegralLogs::create($integral);
                        //HR确认订单，供应商获得收益日志记录
                        Users::where('id',$act_info['user_id'])->increment('profit',$pay_info['money']);//供应商获得收益
                        $profit = [
                            'user_id' => $act_info['user_id'],
                            'user_name' => $user['username'],
                            'profit' => '+'.$pay_info['money'],
                            'desc' => '活动名称:'.$act_info['title'],
                            'type' => 1,
                        ];
                        ProfitLogs::create($profit);
                        //报名成功、推送微信消息
                        if (!empty($user['openid'])){
                            $template_id = 'W4F_jcLE6buTbjGnYLBxb7xz2DvpWUuuQL0-gX0WEA0';
                            $url = 'http://wap.hrqidian.com/#/myActive';
                            $data = [
                                'first' => '您已成功报名<'.$act_info['title'].'>活动，小启非常重视这次活动',
                                'keyword1' => $act_info['title'],
                                'keyword2' => $act_info['start_at'],
                                'keyword3' => $act_info['place'],
                                'remark' => '请您仔细查看活动要求按时参加，如有变化请第一时间通知活动举办者。 HR小启客服',
                            ];
                            Wechat::wechatSend($user['openid'], $template_id, $url, $data);
                        }
                    }
                    return 'SUCCESS';// 返回处理完成
                }catch (\Exception $e) {

                }
            }
        });
        return $response;
    }

    /**
     * 供应商余额充值支付回调
     */
    public function balanceNotifyUrl()
    {
        $app = Factory::payment($this->wxConfig);
        $response = $app->handlePaidNotify(function ($message, $fail) {
            //处理订单
            if ($message["result_code"] == "SUCCESS" && $message["return_code"]) {
                try{
                    //支付单信息
                    $pay_info = BalanceLogs::where("pay_sn", $message["out_trade_no"])->first();
                    if($pay_info["pay_state"]==1){
                        //修改订单信息
                        $pay_info->pay_state = 2;
                        $pay_info->pay_at = date('Y-m-d H:i:s');
                        $pay_info->save();

                        Users::where('id',$pay_info['user_id'])->increment('balance',$pay_info['money']);//余额增加
                        Users::where('id',$pay_info['user_id'])->increment('integral',$pay_info['money']);//充值赠送积分
                        //添加日志记录
                        $integral = [
                            'user_id' => $pay_info['user_id'],
                            'user_name' => $pay_info['user_name'],
                            'integral' => '+'.$pay_info['money'],
                            'type' => 1,
                            'desc' => '充值送积分',
                        ];
                        IntegralLogs::create($integral);
                        //发送站内信-积分增加通知
                        $template = [
                            'title' => '赠送积分通知',
                            'content' => '您余额充值了' . $pay_info['money'] . '元,并获得相应的积分',
                            'user_id' => $pay_info['user_id'],
                            'status' => 1,
                            'type' => 1,
                        ];
                        Mails::create($template);
                        //充值成功、推送微信消息
                        if (!empty($userinfo['openid'])){
                            $template_id = 'ZpWXy75XCWVQ8u5URWmq5Pie0HJFbmxpHtEfKC8zWwg';
                            $url = 'http://wap.hrqidian.com/#/financial';
                            $data = [
                                'first' => '您本次充值成功，小启谢谢老板的支持',
                                'keyword1' => $pay_info['money'].'元',
                                'keyword2' => '充值成功',
                                'remark' => '欢迎使用HR一站式采购平台，获取生意更快更精准。 HR小启客服',
                            ];
                            Wechat::wechatSend($userinfo['openid'], $template_id, $url, $data);
                        }
                    }
                    return 'SUCCESS';// 返回处理完成
                }catch (\Exception $e) {

                }
            }
        });
        return $response;
    }
}